-module(mod_math).

-export([run/3]).

run(MM, ArgC, ArgS) ->
	io:format("mod_math:run starting ~n ArgC=~p ArgS=~p~n", [ArgC, ArgS]),
	loop(MM).

%% 这里的MM 就是lib_chan:start_port_instance/2里的S,就是代表着服务器进程的Pid
loop(MM) ->
	%% loop知道S会给我发消息，我也知道要返回消息给S
	receive 	
		{chan, MM, {factorial, N}} ->
			MM ! {send, fac(N)},
			loop(MM);
		{chan, MM, {fibonacci, N}} ->
			MM ! {send, fib(N)},
			loop(MM);
		{chan_close, MM} ->
			io:format("mod_math stoppng~n"),
			exit(normal)
	end.


fac(0) -> 1;
fac(N) -> N * fac(N-1).

fib(1) -> 1;
fib(2) -> 1;
fib(N) -> fib(N -1) + fib(N -2).